#include "convertprocess.h"
#include <QRegularExpression>
#include <QString>

convertProcess::convertProcess(QObject *parent)
    : QObject(parent), m_process(nullptr)
{
    m_process = new QProcess(this);
    connect(m_process, &QProcess::started, this, &convertProcess::onProcessStarted);
    connect(m_process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &convertProcess::onProcessFinished);
    connect(m_process, &QProcess::readyReadStandardError, this, &convertProcess::onReadyReadStandardError);
}

convertProcess::~convertProcess()
{
    // m_process 作为子对象会自动释放
}

void convertProcess::stopProcess()
{

    if(m_process && m_process->state() == QProcess::Running){
        m_process->kill();
    }
}

void convertProcess::startProcess(const QString& file_Name, const QString &in_Fmt, const QString &out_Fmt, const QString& output_Name)
{
    this->file_Name = file_Name;
    this->input_Fmt = in_Fmt;
    this->output_Fmt = out_Fmt;
    this->output_Name = output_Name;

    QStringList ffmpeg_Cmd;
    ffmpeg_Cmd << "-i" << file_Name + "." + input_Fmt << output_Name + "." + output_Fmt << "-y"; // 覆盖
    qDebug() << ffmpeg_Cmd;

    m_process->start(ffmpeg_Path, ffmpeg_Cmd);
}

void convertProcess::onProcessStarted()
{
    qDebug() << "ffmpeg 进程已启动";
}

void convertProcess::onProcessFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
    if (exitStatus == QProcess::NormalExit) {
        qDebug() << "进程正常结束，退出码:" << exitCode;
    } else {
        qWarning() << "进程未正常结束，退出码:" << exitCode;
    }
}

void convertProcess::onReadyReadStandardError()
{
    QByteArray standardError = m_process->readAllStandardError();
    QString errorString = QString::fromUtf8(standardError);

    // 尝试解析总时长信息
    QRegularExpression durationRegex(R"(Duration:\s*(.*))");
    QRegularExpressionMatch durationMatch = durationRegex.match(errorString);
    if (durationMatch.hasMatch()) {
        QString result = durationMatch.captured(1);
        totalMilliSeconds = convertToMilliSeconds(result.mid(0, 2).toInt(), result.mid(3, 2).toInt(),
                                                  result.mid(6, 2).toInt(), result.mid(9, 2).toInt());
    }

    // 解析进度信息，ffmpeg 输出的进度信息格式为 "frame=... time=... bitrate=... speed=... "
    QRegularExpression regex(R"(time=(\d+):(\d+):(\d+)\.(\d+))");
    QRegularExpressionMatch match = regex.match(errorString);
    if (match.hasMatch()) {
        int hours = match.captured(1).toInt();
        int minutes = match.captured(2).toInt();
        int seconds = match.captured(3).toInt();
        int milliseconds = match.captured(4).toInt();

        long long currentTime = convertToMilliSeconds(hours, minutes, seconds, milliseconds);
        if (totalMilliSeconds > 0) {
            double progress = static_cast<double>(currentTime) / totalMilliSeconds * 100;
            emit progressUpdated(progress);
        }
    }
}

long long convertProcess::convertToMilliSeconds(int hours, int minutes, int seconds, int milliseconds)
{
    return hours * 3600 * 1000LL + minutes * 60 * 1000LL + seconds * 1000LL + milliseconds;
}
